package com.typhosoft.jcommon.network;

import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.util.InputStreamSender;
import com.typhosoft.jcommon.bean.CPhoto;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 * Created by Mario on 24/03/2014.
 */
public class CSendActivity extends Thread {
    private final Connection client;
    private final CPhoto photo;

    public CSendActivity(CPhoto photo, Connection client) {
        super("CSendActivity-" + photo.getUser());
        this.photo = photo;
        this.client = client;
    }

    @Override
    public void run() {
        try {
            ByteArrayOutputStream b = new ByteArrayOutputStream();
            ObjectOutputStream o = new ObjectOutputStream(b);
            o.writeObject(photo);
            final ByteArrayInputStream in = new ByteArrayInputStream(b.toByteArray());
            client.addListener(new InputStreamSender(in, 512) {
                @Override
                protected void start() {
                    CNetwork.PhotoSize size = new CNetwork.PhotoSize();
                    size.photoSize = in.available();
                    client.sendTCP(size);
                }

                @Override
                protected Object next(byte[] bytes) {
                    return bytes;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
